package com.yufei.infoExtractor.util;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.imageio.ImageIO;

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.log4j.Logger;

import com.yufei.infoExtractor.exception.TaskResultExportException;
import com.yufei.infoExtractor.pfw.entity.Entity;




/**
 * @author zhaoyufei
 * 
 *         zhao-0244@qq.com
 */
public class FileUtil {
	private static Logger logger = Logger.getLogger(FileUtil.class);

	public static List<List> listToBeans(List<List<String>> source,
			List<String> beans, List<String> fieldOrders, String excelPath) {
		List<String> rowValues = null;
		String beanName = null;
		Object obj = null;
		List<String> columns = null;
		List<List> list = new ArrayList();
		List<Object> objList = null;
		Object[] objs = null;
		for (int i = 0; i < source.size(); i++) {
			objList = new ArrayList();
			// per row
			rowValues = source.get(i);
			objs = new Object[beans.size()];
			// per column
			for (int q = 0; q < beans.size(); q++) {
				beanName = beans.get(q);

				try {
					objs[q] = Class.forName(beanName).newInstance();
				} catch (InstantiationException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IllegalAccessException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (ClassNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

			for (int j = 0; j < rowValues.size(); j++) {

				for (int q = 0; q < beans.size(); q++) {

					try {
						BeanUtils.setProperty(objs[q], fieldOrders.get(j),
								rowValues.get(j));
						// PropertyUtils.setProperty(objs[q],
						// fieldOrders.get(j), rowValues.get(j));
					} catch (IllegalAccessException e) {
						// TODO Auto-generated catch block
						continue;
					} catch (InvocationTargetException e) {
						// TODO Auto-generated catch block
						continue;
					}

				}
			}
			for (Object obj1 : objs) {
				objList.add(obj1);
			}
			list.add(objList);
		}
		return list;

	}

	public static List<List<String>> parseExcelFile(String filePath)
			throws Exception {
		Workbook wb = null;
		wb = Workbook.getWorkbook(new FileInputStream(filePath));
		Sheet sheet = wb.getSheet(0);
		int rows = sheet.getRows();
		int cols = sheet.getColumns();
		String content = null;
		// String[] rowValue=null;
		List<String> rowValue = null;
		List rowValueList = new ArrayList();
		for (int rowNumber = 1; rowNumber < rows + 1; rowNumber++) {
			rowValue = new ArrayList<String>();
			Cell[] rowCells = sheet.getRow(rowNumber - 1);
			for (int cellNumber = 1; cellNumber < cols + 1; cellNumber++) {
				content = rowCells[cellNumber - 1].getContents();


				rowValue.add(content);
				// rowValue[cellNumber-1]=rowCells[cellNumber-1].getContents();
			}
			rowValueList.add(rowValue);
		}

		return rowValueList;
	}

	/**
	 * @param <T>
	 * @param source
	 * @param fieldOder
	 *           将实体集合导出到Excel表中
	 * @throws Exception
	 */
	public static <T> String gernerateExcelFromList(List<T> source,
			List<String> fieldOder, String savePath,List<String> headers) throws Exception {

            return FileUtil.gernerateExcelFromList(source, fieldOder, savePath, headers, null);

	}
	
	
	
	/**
	 * @param <T>
	 * @param source
	 * @param fieldOder
	 *           将实体集合导出到Excel表中
	 * @throws Exception
	 * 如果source为空或者null则直接返回null,
	 * fieldOder以及headers可以为空或者null
	 */
	public static <T> String gernerateExcelFromList(List<T> source,
			List<String> fieldOder, String savePath,List<String> headers,String fileName) throws Exception {
		if(CommonUtil.isEmptyOrNull(source)){
			
			return null;
		}
	
		if(CommonUtil.isEmptyOrNull(fieldOder)){
			fieldOder=new ArrayList<String>();

			List<Field> fields=CommonUtil.getAllDeclareFields(source.get(0).getClass());
			for(Field field:fields){
				fieldOder.add(field.getName());
			}
		}
	
		
		if(!new File(savePath).exists()){
			new File(savePath).mkdir();
		}
		if(CommonUtil.isEmptyOrNull(fileName)){
			 fileName=System.currentTimeMillis()+".xls";

		}
		WritableWorkbook workbook = Workbook.createWorkbook(new File(savePath+fileName));
		WritableSheet sheet = workbook.createSheet("sheet", 0);
		Label label = null;
		String[] strs = new String[fieldOder.size()];;
		int rowNumber = 0, columnNumber = 0;
	if(!CommonUtil.isEmptyOrNull(headers)){
		for (int j = 0; j < strs.length; j++) {

			// column,row
			label = new Label(columnNumber, rowNumber, headers.get(j));
			sheet.addCell(label);
			columnNumber++;
		}
		rowNumber++;
	    
	}
		
	    
	    
		for (T t : source) {
			columnNumber = 0;
			// per row
			
			for (int i = 0; i < fieldOder.size(); i++) {
				strs[i] = (String) BeanUtils.getProperty(t,
						fieldOder.get(i));
			}
			for (int j = 0; j < strs.length; j++) {

				// column,row
				label = new Label(columnNumber, rowNumber, strs[j]);
				sheet.addCell(label);
				columnNumber++;
			}
			rowNumber++;
		}

		workbook.write();
		workbook.close();
		return fileName;

	}
   /* public  static void generatePdf(){
    	Document document=new Document();
    	try {
    		PdfWriter.getInstance(document, new FileOutputStream("E://temp.pdf"));
    		document.open();
    		document.add(new Paragraph("Hello Wrold"));
    		document.close();
    	} catch (Exception e) {
    		// TODO: handle exception
    	}
    }*/
	
	public static void main(String[] args) {
		
		


		/*List list1 = new ArrayList();
		list1.add("com.ourpalm.mis.object.business.Service");
		list1.add("com.ourpalm.mis.object.business.ServiceDetail");
		String[] orders = { "service_id", "service_name", "service_fee_type",
				"service_fee", "service_validtime",
				"service_audit_passed_time", "service_audit_time",
				"service_status", "service_open", "cpservice_id", "", "cpid",
				"spid", "billing_A", "billing_B", "compony_id",
				"service_description" };
		List fieldOrder = new ArrayList();
		for (String str : orders) {
			fieldOrder.add(str);
		}
		try {
			List list = FileUtil.parseExcelFile("D:\\Book1.xls");
			FileUtil.listToBeans(list, list1, fieldOrder, null);
			// System.out.print();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
*/
	}

	/**
	 * @param savedDirectory
	 * @param saveFileName
	 *            :务必使全名（即使要有格式）
	 * @param input
	 * @throws IOException
	 */
	public static void makeFile(String savedDirectory, String saveFileName,
			InputStream input) throws IOException {
		BufferedImage srcImage;
	
		srcImage = ImageIO.read(input);
	
		ImageIO.write(srcImage, "JPEG", new File(savedDirectory + saveFileName));
		input.close();
		/*
		 * File file=new File(savedDirectory+saveFileName); if(!file.exists()){
		 * file.createNewFile(); }
		 * 
		 * FileOutputStream fileOutputStream=new FileOutputStream(file); byte[]
		 * buffer=new byte[512]; while(input.read(buffer)!=-1){
		 * fileOutputStream.write(buffer);
		 * 
		 * } fileOutputStream.close();
		 */
	}

	public static void makeFile(String savedDirectory, String saveFileName,
			String input) throws IOException {
		if(CommonUtil.isEmptyOrNull(savedDirectory)||CommonUtil.isEmptyOrNull(saveFileName)||CommonUtil.isEmptyOrNull(input)){
			throw new IllegalArgumentException();
		}
		 File file=new File(savedDirectory+saveFileName);
		 if(!file.exists()){
		 file.createNewFile(); }
		 byte[] bytes=input.getBytes();
		 FileOutputStream fileOutputStream=new FileOutputStream(file);
		 byte[] buffer=new byte[512]; 
	     fileOutputStream.write(bytes);
	     fileOutputStream.close();
		 
	}
	/**
	 * @param taskResultList
	 * @param taskName
	 * @param taskStartedTime
	 * 
	 * 每个任务采集之后都会将采集结果写入一个文件夹，文件夹的名称格式是：任务名称+任务采集开始时间
	 * @throws TaskResultExportException 
	 */
	public static void makeFileForTaskResult(List<? extends Entity> taskResultList,String destinationFoler,Class entityClass) throws TaskResultExportException{
		if(CommonUtil.isEmptyOrNull(taskResultList)){
			
			return;
		}
		String taskSavedDirectory=AppUtil.getInfoExtractorConfig().getFileSavedDirectory()+destinationFoler;
		File file=new File(taskSavedDirectory);
	    if(!file.exists()){
	    	file.mkdirs();
	    }
		
		
		for(Entity  entity:taskResultList){
			try {
				CommonUtil.generateXmlForObject(entity, entityClass, taskSavedDirectory);
			} catch (IOException e) {
				// TODO Auto-generated catch block
throw	new TaskResultExportException(ExceptionUtil.getExceptionDetailsMessage(e));
}
		}
		
		
		
	}
	public static void makeExcelFileForTaskResult(List<? extends Entity> taskResultList,String destinationFoler,Class entityClass) throws Exception{

      FileUtil.gernerateExcelFromList(taskResultList, null, destinationFoler, null);
		
		
	}

}
